<template>
  <div>
    <zm-dialog
      :title="dialogTitle"
      :visible.sync="value"
      append-to-body
      size="large"
      :before-close="dialogClose"
      :close-on-click-modal="false"
    >
      <zm-form :model="form" ref="zmForm" :rules="rules" label-width="100px">
        <zm-form-item label="产品状态" v-if="type !== '4'">
          <span>{{ form.isActive === "1" ? "已激活" : "未激活" }}</span>
        </zm-form-item>
        <zm-form-item prop="isCode" label="退货类型" v-if="type !== '4'">
          <zm-data-radio
            v-model="form.isCode"
            :list="codeList"
            :disabled-value="disabledValue"
          ></zm-data-radio>
        </zm-form-item>
        <div v-if="form.isCode === '0'">
          <!-- 点卡 且为自定义金额时 -->
          <zm-form-item
            prop="customizePrice"
            v-if="infoData.productType === '3' && infoData.isCustomize === '1'"
          >
            <zm-table-data
              :data="form.customizePrice"
              :columns="returnCustomizeColumns"
              :show-page="false"
            ></zm-table-data>
          </zm-form-item>
          <zm-form-item prop="refundNumber" label="退货数量" v-else>
            <zm-input
              v-model="form.refundNumber"
              @input="changeNumber"
              placeholder="请输入退货数量"
              class="w300"
            >
              <span slot="append">张</span>
            </zm-input>
          </zm-form-item>
          <zm-form-item prop="canBackNum" label="可退数量">
            <span>{{ form.canBackNum }}张</span>
          </zm-form-item>

          <zm-form-item
            prop="unBackNum"
            label="不可退数量"
            v-if="form.isActive === '1'"
          >
            <span>{{ form.unBackNum || 0 }}张</span>
          </zm-form-item>
          <zm-form-item prop="" label="退货金额">
            <span>{{
              form.refundAmount ? "￥" + form.refundAmount : "--"
            }}</span>
          </zm-form-item>
        </div>
        <div v-if="form.isCode === '1'">
          <zm-form-item
            label="输入号段"
            v-if="form.isCode === '1'"
            prop="codeIdDetail"
          >
            <div
              v-for="(item, index) in form.codeIdDetail"
              :key="index"
              class="mt5"
            >
              <zm-form-item prop="left" class="dib mb0">
                <zm-input
                  v-model="item.left"
                  @change="changeCode"
                  class="w200"
                ></zm-input>
              </zm-form-item>
              <span>-</span>
              <zm-form-item prop="right" class="dib mb0">
                <zm-input
                  v-model="item.right"
                  @change="changeCode"
                  class="w200"
                ></zm-input>
              </zm-form-item>
              <span @click="addItem">
                <i
                  class="el-icon-circle-plus-outline text-primary fs24 iconReturnClass"
                ></i>
              </span>
              <span @click="deleteItem(index)" v-if="index !== 0" class="ml5">
                <i
                  class="el-icon-circle-close text-error fs24 iconReturnClass"
                ></i>
              </span>
            </div>
          </zm-form-item>
          <!-- <zm-form-item
            label="可退号段"
            v-if="form.canUseNumber && form.canUseNumber.length > 0"
          >
            <span v-for="(item, index) in form.canUseNumber" :key="index">
              <span> {{ item.left }}-{{ item.right }}</span>
              <span v-if="index < form.canUseNumber.length - 1">、</span>
            </span>
            <div class="text-error">
              共{{ form.appointcNum }}张,{{ form.appointUnBackNum }}张不可用
            </div>
          </zm-form-item> -->
          <zm-form-item>
            <zm-button @click="goValidate">号段验证</zm-button>
            <span class="text-error vm" v-if="form.canUseNumber && form.canUseNumber.length > 0">
              共{{ form.appointcNum }}张,{{ form.appointUnBackNum }}张不可退
            </span>
          </zm-form-item>
          <zm-form-item
            label="可退号段"
            v-if="form.canUseNumber && form.canUseNumber.length > 0"
          >
            <span v-for="(item, index) in form.canUseNumber" :key="index">
              <span> {{ item.left }}-{{ item.right }}</span>
              <span v-if="index < form.canUseNumber.length - 1">、</span>
            </span>
          </zm-form-item>
          <zm-form-item label="可退数量">
            <span>{{ form.appointCanBackNum || "--" }}张</span>
          </zm-form-item>
          <zm-form-item label="退货数量">
            <span>{{ form.appointRefundNumber || "--" }}张</span>
          </zm-form-item>
          <zm-form-item label="退货金额">
            <span>{{
              form.appointPrice ? "￥" + form.appointPrice : "--"
            }}</span>
          </zm-form-item>
        </div>

        <zm-form-item prop="remark" label="退货说明">
          <zm-input
            v-model="form.remark"
            type="textarea"
            :maxlength="300"
            class="w500"
            placeholder="请输入退货说明,便于审批人员查看"
          ></zm-input>
        </zm-form-item>
      </zm-form>
      <div slot="footer" class="tr">
        <zm-button @click="dialogClose" type="">取消</zm-button>
        <zm-button v-if="refundId" @click="save" type="primary">
          保存
        </zm-button>
        <zm-button v-if="!refundId" @click="save('approval')" type="primary">
          提交审批
        </zm-button>
      </div>
    </zm-dialog>
  </div>
</template>

<script>
import dialogMixin from '@/mixins/dialogMixin'
import saleOrderApi from '@/api/src/saleOrder'
import approveProcessApis from '@/api/src/approve'
import validateRule from '@/utils/validateRule'
import { returnCustomizeColumns } from './const'
import { PROCESS_TYPE } from '@/model'
export default {
  mixins: [dialogMixin],
  props: {
    infoData: {
      type: Object,
      default () {
        return {}
      }
    },
    orderId: {
      type: String,
      default: ''
    },
    type: {
      type: String
    },
    refundId: { type: String, default: '' }
  },
  data () {
    const validCode = (rule, value, cb) => {
      let noFill =
        value &&
        value.filter(i => {
          return i.left === '' && i.right === ''
        })
      if (noFill.length > 0) {
        cb(new Error('号段区间至少填写一个'))
      } else {
        cb()
      }
    }
    const numberValid = (rule, value, cb) => {
      if ((+value > +this.form.canBackNum && this.type !== '4') || (+value > +this.form.number && this.type === '4')) {
        cb(new Error('退货数量不能大于可退数量'))
      } else {
        cb()
      }
    }
    const customizeValid = (rule, value, cb) => {
      let arr = value.filter(i => {
        return (
          +i.customizeRefund > +i.num ||
          !/^[1-9]{0,}[\d]*$/.test(+i.customizeRefund)
        )
      })
      if (arr && arr.length > 0) {
        arr.map(i => {
          if (+i.customizeRefund > +i.num) {
            cb(new Error('退货数量不能大于可退数量'))
          } else if (!/^[1-9]{0,}[\d]*$/.test(+i.customizeRefund)) {
            cb(new Error('请输入正整数!'))
          } else {
            cb()
          }
        })
      } else {
        cb()
      }
    }
    return {
      isValidButton: true,
      form: {
        isCode: '0',
        codeIdDetail: [
          {
            left: '',
            right: ''
          }
        ],
        totalNum: '',
        refundNumber: '',
        canBackNum: '',
        unBackNum: '',
        refundAmount: '',
        customizePrice: [],
        remark: '',
        // 给指定号段用的参数
        appointcNum: '', // 输入的号段总数
        appointRefundNumber: '', // 退货数量
        appointCanBackNum: '', // 可退数量
        appointUnBackNum: '', // 不可退
        appointPrice: '', // 退货金额
        canUseNumber: [] // 可用号段
      },
      processType: PROCESS_TYPE.saleOrderRefund,
      rules: {
        codeIdDetail: [
          {
            required: true,
            validator: validCode,
            triggq: 'blur'
          }
        ],
        refundNumber: [
          {
            validator: validateRule.integer,
            trigger: 'blur'
          },
          {
            required: true,
            validator: numberValid
          }
        ],
        customizePrice: [
          {
            validator: customizeValid,
            trigger: 'blur'
          }
        ],
        remark: [
          {
            required: true,
            message: '请输入退货说明',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  computed: {
    dialogTitle () {
      return this.refundId ? '编辑产品退货' : '产品退货'
    },
    returnCustomizeColumns () {
      return returnCustomizeColumns(this)
    },
    codeList () {
      let list = [
        {
          name: '系统自动作废',
          value: '0'
        },
        {
          name: '指定号段作废',
          value: '1'
        }
      ]
      return this.form.isActive === '1'
        ? list
        : list.filter(i => i.value === '0')
    },
    disabledValue () {
      // return this.form.isActive === '1' ? '' : '1'
      return this.refundId && this.form.isActive === '1'
        ? '0,1'
        : this.refundId && this.form.isActive === '0'
          ? '0'
          : ''
    }
  },
  created () {
    this.getInfo()
  },
  methods: {
    async getInfo () {
      let params = this.refundId
        ? { refundId: this.refundId }
        : { orderId: this.orderId }
      const _res = await saleOrderApi.getRefund(params)
      let sampleValue = {
        orderNo: _res.orderNo,
        customerName: _res.customerName,
        isActive: _res.isActive,
        isCode: _res.isCode,
        totalNum: _res.totalNum,
        remark: _res.remark,
        isCustomize: _res.isCustomize,
        customizePrice: _res.customizePrice
          ? _res.customizePrice.map(i => {
            return {
              ...i,
              customizeRefund: '0'
            }
          })
          : [],
        codeIdDetail:
          _res.codeIdDetail && _res.codeIdDetail.length > 0
            ? _res.codeIdDetail
            : [{ left: '', right: '' }]
      }
      let formValue
      if (_res.isCode === '0') {
        formValue = {
          refundNumber: _res.refundNumber,
          canBackNum: _res.canBackNum,
          unBackNum: _res.unBackNum,
          refundAmount: _res.refundAmount,
          number: _res.number
        }
      } else {
        formValue = {
          codeIdDetail: _res.codeIdDetail,
          canUseNumber: JSON.parse(JSON.stringify(_res.codeIdDetail)), // 待确认
          appointcNum: _res.cNum,
          appointRefundNumber: _res.refundNumber,
          appointCanBackNum: _res.canBackNum,
          appointUnBackNum: _res.unBackNum,
          appointPrice: _res.refundAmount,
          number: _res.number
        }
      }
      this.form = { ...formValue, ...sampleValue }
      console.log(this.form, 'fjbjkh')
    },

    changeNumber () {
      let totalPrice
      totalPrice = (
        (+this.infoData.saleTotalPrice / +this.infoData.number) *
        +this.form.refundNumber
      ).toFixed(2)

      this.$set(this.form, 'refundAmount', totalPrice)
    },
    customizeRefund () {
      let scale = this.form.customizePrice.map(
        item => (+item.totalPrice / +item.num) * +item.customizeRefund
      )
      let customizeRefund = scale.reduce((n, m) => n + m).toFixed(2)
      this.$set(this.form, 'refundAmount', customizeRefund)
    },
    addItem () {
      let defaultItem = {
        left: '',
        right: ''
      }
      this.form.codeIdDetail.push(defaultItem)
    },
    deleteItem (index) {
      this.form.codeIdDetail.splice(index, 1)
    },
    changeCode () {
      this.isValidButton = false
    },
    async goValidate () {
      // 单个验证
      let _valid = false
      this.$refs.zmForm.validateField('codeIdDetail', valid => {
        _valid = valid
      })
      if (_valid) return
      saleOrderApi
        .checkCodeIdDetail({
          orderId: this.orderId,
          codeIdDetail: this.form.codeIdDetail
        })
        .then(_res => {
          this.form = {
            ...this.form,
            appointcNum: _res.cNum,
            appointRefundNumber: _res.refundNumber,
            appointCanBackNum: _res.canBackNum,
            appointUnBackNum: _res.unBackNum,
            appointPrice: _res.refundAmount,
            canUseNumber: _res.codeIdDetail
          }
          this.isValidButton = true
        })
        .catch(() => {
          this.form = {
            ...this.form,
            appointcNum: '',
            appointRefundNumber: '',
            appointCanBackNum: '',
            appointUnBackNum: '',
            appointPrice: '',
            canUseNumber: []
          }
          this.isValidButton = false
        })
    },

    goSuccess () {
      this.$message.success('操作成功')
      this.$emit('after-return', true)
      this.dialogClose()
    },
    async save (buttonType) {
      let _valid = false
      this.$refs.zmForm.validate(valid => {
        _valid = valid
      })
      if (!_valid) return
      if (!this.isValidButton && this.form.isCode === '1') {
        this.$message.info('请先验证正确的号段')
      } else {
        this.$confirm(
          '确定提交退货审批么？将会影响销售提成和销售总额?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
          .then(async () => {
            let params
            if (this.form.isCode === '0') {
              params = {
                orderId: this.orderId,
                isCode: this.form.isCode,
                refundNumber: this.form.refundNumber,
                refundAmount: this.form.refundAmount,
                remark: this.form.remark,
                isCustomize: this.form.isCustomize,
                customizeRefund: this.form.customizePrice
                  ? this.form.customizePrice
                    .map(i => i.customizeRefund)
                    .join(',')
                  : ''
              }
            } else if (this.form.isCode === '1') {
              params = {
                orderId: this.orderId,
                isCode: this.form.isCode,
                refundNumber: this.form.appointRefundNumber,
                canBackNum: this.form.appointCanBackNum,
                refundAmount: this.form.appointPrice,
                remark: this.form.remark,
                codeIdDetail: this.form.canUseNumber
              }
            }
            let finParams = JSON.parse(JSON.stringify(params))
            if (this.refundId) {
              delete finParams.orderId
              finParams = {
                ...finParams,
                refundId: this.refundId
              }
            }
            saleOrderApi.refund(finParams).then(async result => {
              if (buttonType === 'approval') {
                await approveProcessApis.submit({
                  businessId: result.id,
                  processType: this.processType,
                  linkName: this.form.orderNo + this.form.customerName
                })
                this.goSuccess()
              } else {
                this.goSuccess()
              }
            })
          })
          .catch(() => {})
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.iconReturnClass {
  position: relative;
  top: 3px;
}
</style>
